package com.example.ai.handler;

import com.example.ai.entity.DialogueMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 自定义类型处理器（处理 JSON 字段）
 *
 * @author liujian
 */
@MappedTypes(DialogueMessage.class)
public class DialogueMessageTypeHandler extends BaseTypeHandler<DialogueMessage> {
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    DialogueMessage parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, mapper.writeValueAsString(parameter));
        } catch (JsonProcessingException e) {
            throw new SQLException("JSON serialization error", e);
        }
    }

    @Override
    public DialogueMessage getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJson(rs.getString(columnName));
    }

    @Override
    public DialogueMessage getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJson(rs.getString(columnIndex));
    }

    @Override
    public DialogueMessage getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJson(cs.getString(columnIndex));
    }

    private DialogueMessage parseJson(String json) {
        try {
            return mapper.readValue(json, DialogueMessage.class);
        } catch (IOException e) {
            throw new RuntimeException("JSON parsing error", e);
        }
    }
}
